package com.huawei.datastructurelearning.二分查找;

public class Code2 {
    //2024/02/23再次读到二分查找 尝试写出算法
    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 6, 7, 8, 10, 13, 14, 15, 17};

        System.out.println( getIndex(1, arr));
        System.out.println( getIndex(3, arr));
        System.out.println( getIndex(5, arr));
        System.out.println( getIndex(6, arr));
        System.out.println( getIndex(14, arr));
        System.out.println( getIndex(16, arr));
        System.out.println( getIndex(15, arr));
    }

    private static int getIndex(int num, int[] arr) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int middle = (left + right) >>> 1;

            if (arr[middle] < num) {
                left = middle + 1;
            } else if (num < arr[middle]) {
                right = middle - 1;
            } else {
                return middle;
            }
        }
        return -1;
    }
}
